<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索框部分 -->
      <el-row :gutter="20">
        <el-col :span="18">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-input
                v-model="queryInfo.title"
                placeholder="根据角色名搜索"
                clearable
                @clear="getRoles"
              ></el-input>
            </el-col>
            <el-col :span="6">
              <el-button
                class="btn"
                size="small"
                type="primary"
                plain
                @click="getRoles"
                >搜索</el-button
              >
            </el-col>
          </el-row>
        </el-col>

        <el-col :span="6">
          <el-button
            class="roles"
            type="success"
            icon="el-icon-edit"
            @click="addRoles"
            >新增角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 提示信息部分 -->
      <el-alert :title="countstext" type="info" show-icon :closable="false">
      </el-alert>
      <!-- 表格部分 -->
      <el-table v-loading="loading" :data="rolesTableData" style="width: 100%">
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column align="right" prop="title" label="角色名">
        </el-table-column>
        <el-table-column align="right" prop="update_date" label="日期" sortable>
          <template slot-scope="scope">
            {{ scope.row.update_date | dateformat }}
          </template>
        </el-table-column>
        <el-table-column align="right" label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              circle
              plain
              type="primary"
              icon="el-icon-edit"
              @click="showedit(scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              circle
              plain
              type="danger"
              icon="el-icon-delete"
              @click="removeRoles(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 -->
      <el-pagination
        style="text-align: right; margin-top: 20px"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total,prev, pager, next, sizes,  jumper"
        :total="counts"
      >
      </el-pagination>
    </el-card>

    <!-- 新建角色 -->
    <el-dialog
      title="创建角色组"
      label-width="80px"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeadd"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
        style="width: 400px; margin-left: 120px"
      >
        <el-form-item label="角色组名" prop="title">
          <el-input v-model="addForm.title"></el-input>
        </el-form-item>
        <el-form-item label="权限分配">
          <!-- 树节点 -->
          <el-tree
            :default-checked-keys="verify"
            :default-expanded-keys="[1]"
            :data="treeData"
            show-checkbox
            node-key="id"
            ref="treeRef"
            highlight-current
            :props="defaultProps"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑弹框 -->
    <el-dialog
      title="编辑角色组"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="closeedit"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
        style="width: 400px; margin-left: 120px"
      >
        <el-form-item label="角色组名" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="权限分配">
          <el-tree
            :default-checked-keys="verifys"
            :default-expanded-keys="[1]"
            :data="treeData"
            show-checkbox
            node-key="id"
            ref="edittreeRef"
            highlight-current
            :props="defaultProps"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data () {
    return {
      loading: true,
      queryInfo: {
        title: '',
        page: 1,
        pagesize: 2
      },
      counts: 0,
      pagesize: 1,
      pages: 2,
      page: '1',
      countstext: '',
      rolesTableData: [],
      addDialogVisible: false,
      addForm: {
        title: '',
        permissions: this.data
      },
      addFormRules: {
        title: [{ required: true, message: '请填写用户名', trigger: 'blur' }]
      },
      // 树形图的数据
      treeData: [],
      // 树形图的配置
      defaultProps: {
        children: 'childs',
        label: 'title'
      },

      // 编辑框的数据
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        title: [{ required: true, message: '请填写用户名', trigger: 'blur' }]
      },
      // 添加弹框
      verify: [],
      verifys: []
    }
  },
  created () {
    // 获取用户权限列表
    this.getRoles()
  },
  methods: {
    // 获取用户权限列表
    async getRoles () {
      const { data: res } = await this.$http.get('permissions', {
        params: this.queryInfo
      })
      this.rolesTableData = res.list
      this.counts = res.counts
      this.countstext = `共${this.counts}条数据`
      this.loading = false
    },
    handleSizeChange (item) {
      this.queryInfo.pagesize = item
      this.getRoles()
    },
    handleCurrentChange (val) {
      this.queryInfo.page = val
      this.getRoles()
    },

    async addRoles () {
      // 添加弹框出现
      this.addDialogVisible = true
      // 获取菜单列表
      const { data } = await this.$http.get('menus')
      this.treeData = data
    },

    closeadd () {
      this.$refs.addFormRef.resetFields()
    },
    addConfirm () {
      // 表单验证
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        this.verify = [...this.$refs.treeRef.getCheckedKeys()]

        await this.$http.post('permissions', {
          title: this.addForm.title,
          permissions: this.verify
        })
        this.$message.success('添加成功!')
        // 更新视图
        this.getRoles()

        // 关闭弹框
        this.addDialogVisible = false
      })
    },

    closeedit () {
      this.$refs.editFormRef.resetFields()
      this.verifys = []
    },

    async showedit (row) {
      this.editDialogVisible = true
      const { data } = await this.$http.get('menus')
      this.treeData = data
      // 获取权限详情
      const { data: data1 } = await this.$http.get(`permissions/${row.id}`)
      console.log(data1)
      this.editForm = data1
      this.verifys = data1.permissions
    },

    getKeys (node, arr) {
      if (!node.childs) {
        return arr.push(node.id)
      }
      node.childs.forEach((item) => {
        this.getKeys(item, arr)
      })
    },
    async editConfirm () {
      this.verifys = [...this.$refs.edittreeRef.getCheckedKeys()]
      await this.$http.put(`permissions/${this.editForm.id}`, {
        id: this.editForm.id,
        title: this.editForm.title,
        permissions: this.verifys
      })
      this.$message.success('更新成功')
      // 更新视图
      this.getRoles()
      // 关闭弹窗
      this.editDialogVisible = false
    },
    async removeRoles (row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${row}`)
          // if (res.meta.status !== 200) return this.$message.error('删除失败')
          console.log(res)
          this.$http.delete(`permissions/${row.id}`)
          this.getRoles()
          this.editDialogVisible = false
          this.$message.success('删除用户成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  },
  filters: {
    dateformat (time) {
      return new Date(time).toLocaleString()
    }
  }
}
</script>
<style lang="less" scoped>
.el-alert {
  margin: 20px 0;
}
.btn {
  height: 36px;
}
.roles {
  float: right;
}
</style>
